package com.situ.mall.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.common.entity.Attachment;
import com.situ.mall.common.mapper.AttachmentMapper;
import com.situ.mall.common.service.IWXAttachmentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author yangkx
 * @create 2024-04-23-17:40
 */
@Service
public class WXAttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements IWXAttachmentService {

    //文件网络路径
    @Value("${wxFile.path}")
    private String wxFilePath;

    //微信小程序文件的保存地址
    @Value("${wxFile.location}")
    private String wxFileLocation;

    //微信小程序文件上传
    @Override
    public String wxUpload(MultipartFile file) {
        //打印文件名
        System.out.println(file.getOriginalFilename());

        String location = "";
        //给传进去的文件造个新名字，避免重名
        String newFileName = System.currentTimeMillis()
                //从最后一个.开始，向后截取后缀名
                + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            // 这一步相当于在指定的地址占了个位置，下一步才是把文件放到这个位置里
            File f = new File(wxFileLocation + newFileName);
            //1.把文件保存到本地硬盘上的对应目录中
            file.transferTo(f);

            //2.返回该文件的访问路径
            location = wxFilePath + newFileName;
        } catch (Exception e){
            location = "上传文件失败";
        }
        return location;
    }
}
